package avicit.bdp.dds.server.master.dispatch.host.assign;

import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * round robin selector
 * @param <T> T
 */
@Service
public class RoundRobinSelector<T> implements Selector<T> {

    private final AtomicInteger index = new AtomicInteger(0);

    @Override
    public T select(Collection<T> source) {
        if (source == null || source.size() == 0) {
            throw new IllegalArgumentException("Empty source.");
        }

        /**
         * if only one , return directly
         */
        if (source.size() == 1) {
            return (T)source.toArray()[0];
        }

        int size = source.size();
        /**
         * round robin
         */
        return (T) source.toArray()[index.getAndIncrement() % size];
    }
}
